package cn.tomoya.module.api.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.tomoya.common.BaseController;
import cn.tomoya.exception.Result;
import cn.tomoya.module.reply.entity.Reply;
import cn.tomoya.module.reply.service.ReplyService;
import cn.tomoya.module.security.JwtTokenUtil;
import cn.tomoya.module.security.JwtUser;
import cn.tomoya.module.topic.entity.Topic;
import cn.tomoya.module.topic.service.TopicService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * Created by tomoya.
 * Copyright (c) 2016, All Rights Reserved.
 * http://tom.cn
 */
@RestController
@Api(tags = "发表留言回答", description = "APP")
@RequestMapping("/api/reply")
public class ReplyApiController extends BaseController {

    @Autowired
    private ReplyService replyService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 对回复点赞
     *
     * @param replyId
     * @return
     */
    @GetMapping("/up")
    @ResponseBody
    public Result up(Integer replyId) {
        if (replyId != null) {
            User user = getUser();
            replyService.addOneUp(user.getId(), replyId);
            return Result.success();
        }
        return Result.error("点赞失败");
    }

    /**
     * 对回复取消点赞
     *
     * @param replyId
     * @return
     */
    @GetMapping("/unup")
    @ResponseBody
    public Result unup(Integer replyId) {
        if (replyId != null) {
            User user = getUser();
            replyService.reduceOneUp(user.getId(), replyId);
            return Result.success();
        }
        return Result.error("取消点赞失败");
    }


    /**
     * 保存回答
     *
     * @return
     */
    @ApiOperation(value = "保存回答",notes = "保存留言回答的内容",httpMethod = "POST")
    @RequestMapping(value = "/save" ,method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    public Result save(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "提交条件对象topicId:Integer,content:String,token:String", required = true) @RequestBody JSONObject replyvo) {
       Result result =new Result();
        Integer  topicId =(Integer) replyvo.get("topicId");
        String content = (String)replyvo.get("content");
        String token =(String) replyvo.get("token");
        JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(token);
        String tokenUserName = jwtUsr.getUsername();
        String errors=null;
        if(tokenUserName== null || "".equals(tokenUserName)){
//            跳转登录
            /*return render("/login");*/
            errors="没有登录";
            return result.error(201,errors);
        }
        if (topicId != null) {
            Topic topic = topicService.findById(topicId);
            if (topic != null) {
//                User user = getUser();
                User user=userService.findByUsername(tokenUserName);
                Reply reply = new Reply();
                reply.setUser(user);
                reply.setTopic(topic);
                reply.setInTime(new Date());
                reply.setUp(0);
                reply.setContent(content);
                reply.setReplyReplyCount(0);
                replyService.save(reply);
                result.setDetail(reply);
                //回复+1
                topic.setReplyCount(topic.getReplyCount() + 1);
                topicService.save(topic);
            }
        }
        return result;
    }


    @ApiOperation(value = "留言的回答页面",notes = "根据留言的id查询回答" ,httpMethod = "GET",response = Reply.class)
    @RequestMapping(value = "/{topicId}/{size}/{p}",method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result replies(HttpServletRequest request,@PathVariable("topicId")@ApiParam(value = "回答的id") Integer topicId,@PathVariable("size")@ApiParam(value = "每页条数") Integer size,@PathVariable("p")@ApiParam(value = "当前页数") Integer p){
        Page<Reply> page =replyService.findByTopicId(p == null ? 1 : p,size,topicId);
        Result result = new Result();

        String authorization = request.getHeader("Authorization");
        if(authorization!=null){
            JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(authorization);
            String tokenUserName = jwtUsr.getUsername();
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(tokenUserName);
            User user = userService.findByUsername(tokenUserName);
            String username = user.getUsername();
            if(username.equals(tokenUserName)){
                return result.success(page);
            } else{
                return result.error(400,"没有权限");
            }

        }else{
            return result.error(400,"没有权限");
        }

//        result.setDetail(page);

    }
}
